package apptoko.com;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.CommentFBSuccess;
import apptoko.com.event.Event.ConvertLinkFail;
import apptoko.com.event.Event.ConvertLinkSuccess;
import apptoko.com.event.Event.FeedListFailEvent;
import apptoko.com.event.Event.GetFeedLikesSuccess;
import apptoko.com.event.Event.LikeFailEvent;
import apptoko.com.event.Event.LikeSuccessEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.event.Event.UnLikeFailEvent;
import apptoko.com.event.Event.UnLikeSuccessEvent;
import apptoko.com.event.Event.getFeedCommentFail;
import apptoko.com.event.Event.getFeedCommentSuccess;
import apptoko.com.model.FBFeedItem;
import apptoko.com.model.FBFeedItem.FBComments;
import apptoko.com.model.FBFeedItem.FBLikes;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.NewsFeedListView;
import apptoko.com.view.PullToRefreshListView;
import apptoko.com.view.PullToRefreshListView.OnRefreshListener;
import apptoko.com.view.SuperNewsFeedListView.OnLoadMoreListener;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class FeedDetailsActivity extends SherlockFragmentActivity implements OnLoadMoreListener, OnRefreshListener, OnClickListener, LoginListener {

	private AQuery aq;
	private BackgroundTasks bgTask;
	private EventBus eventBus;
	private ProgressDialog pDialog;
	//private DownloadManager mDownloadManager;
	private Bundle data;
	private int commentLimit = 50;
	private NewsFeedListView listView;
	private FBCommentAdapter adapter;
	private List<FBComments> commentList;
	private View headerView;
	private AQuery headerAQ;
	private String objectId;
	private ArrayList<String> pulledLink;
	private String httpURL;
	private String postTitle;
	private Typeface tf;
	private boolean userLikes;
	private FBLoginManager fbLoginManager;
	private String FB_APP_ID;
	private String action;
	private boolean isLoadMore = false;
	private String accessToken;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_feed_details);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		tf = Typeface.createFromAsset(getAssets(), getString(R.string.roboto_medium));
		data = getIntent().getExtras();
		String title = data.getString(Constants.NEWSFEED_TITLE);
		String image = data.getString(Constants.NEWSFEED_IMAGE);
		objectId = data.getString(Constants.NEWSFEED_ID);
		//canLike = data.getBoolean(Constants.NEWSFEED_CAN_LIKE);
		userLikes = data.getBoolean(Constants.NEWSFEED_USER_LIKES);
		System.err.println(objectId);
		pulledLink = Utils.pullLinks(title);
		bgTask = new BackgroundTasks(this);
		aq = new AQuery(this);
		eventBus = EventBus.getDefault();
		EasyTracker.getInstance().setContext(this);
		listView = (NewsFeedListView) findViewById(R.id.list_fb_comment);
		headerView = getLayoutInflater().inflate(R.layout.feed_details_header, null);
		headerAQ = new AQuery(headerView);
		if(pulledLink.size() > 0){
			httpURL = pulledLink.get(0);
			headerAQ.id(R.id.btn_install).visible().clicked(this);
		} else {
			httpURL = "";
			headerAQ.id(R.id.btn_install).invisible();
		}
		postTitle = title.replace("[News] ", "").replace("[sNews] ", "").replace(httpURL, "");
		getSupportActionBar().setTitle(postTitle);
		headerAQ.id(R.id.image).image(image, false, true, 0, 0, null, AQuery.FADE_IN, AQuery.RATIO_PRESERVE);
		headerAQ.id(R.id.content).text(postTitle);
		if(userLikes){
			headerAQ.id(R.id.btn_like).text(R.string.unlike_action);
		} else {
			headerAQ.id(R.id.btn_like).text(R.string.like_action);
		}
		headerAQ.id(R.id.btn_like).clicked(this);
		if(httpURL.contains("?id=")){
			headerAQ.id(R.id.btn_install).text(R.string.menu_install).clicked(this);
		} else {
			headerAQ.id(R.id.btn_install).text(R.string.download).clicked(this);
		}
		aq.id(R.id.btn_send).clicked(this);
		listView.addHeaderView(headerView);
		commentList = new ArrayList<FBFeedItem.FBComments>();
		adapter = new FBCommentAdapter(this, R.layout.comment_fb_item, commentList);
		listView.setAdapter(adapter);
		listView.setOnLoadMoreListener(this);
		listView.setOnRefreshListener(this);
		getLikes(objectId);
		getComments(objectId, commentLimit);
	}
	
	private void getComments(String id, int limit){
		bgTask.getFeedComments(id, limit);
	}
	
	private void getLikes(String id){
		bgTask.getFeedLikes(id);
	}
	
	public void onEventMainThread(GetFeedLikesSuccess e){
		FBLikes likes = e.getLikesData();
		String user1 = likes.getLikesPersons().get(0).getName();
		String user2 = likes.getLikesPersons().get(1).getName();
		if(user1.equalsIgnoreCase("null")){
			user1="other";
		}
		if(user2==null||user2.equalsIgnoreCase("null")){
			user2="other";
		}
		if(likes.getLikesPersons().size()==2){
			headerAQ.id(R.id.like_number).text(Html.fromHtml(String.format(getString(R.string.like_str_short), user1,user2)));
		}else{
			headerAQ.id(R.id.like_number).text(Html.fromHtml(String.format(getString(R.string.like_str), user1,user2, likes.getLikesPersons().size() - 2)));
		}
		listView.onLoadMoreComplete();
		listView.completeRefreshing();
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}
//	
//	private void startDownloadService() {
//		Intent intent = new Intent();
//		intent.setClass(this, DownloadService.class);
//		startService(intent);
//	}
	
	public void onEventMainThread(getFeedCommentSuccess event){
		List<FBComments> list = event.getCommentList();
		if(isLoadMore){
			for(int i = commentLimit - 50; i < list.size(); i++){
				commentList.add(list.get(i));
			}
			aq.id(R.id.progress).gone();
			aq.id(R.id.text_no_comment).gone();
			aq.id(R.id.btn_retry).gone();
			aq.id(R.id.list_fb_comment).visible();
			aq.id(R.id.layout_send_comment).visible();
			listView.onLoadMoreComplete();
			listView.completeRefreshing();
			adapter.notifyDataSetChanged();
		} else {
			for(FBComments comment : list){
				commentList.add(comment);
			}
			aq.id(R.id.progress).gone();
			aq.id(R.id.text_no_comment).gone();
			aq.id(R.id.btn_retry).gone();
			aq.id(R.id.list_fb_comment).visible();
			aq.id(R.id.layout_send_comment).visible();
			listView.onLoadMoreComplete();
			listView.completeRefreshing();
			adapter.notifyDataSetChanged();
		}
		if(list.size() < commentLimit){
			listView.setOnLoadMoreListener(null);
		}
	}
	
	private class FBCommentAdapter extends ArrayAdapter<FBComments>{

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				convertView = getLayoutInflater().inflate(R.layout.comment_fb_item, null);
				holder = new ViewHolder();
				holder.avatar = (ImageView) convertView.findViewById(R.id.user_avatar);
				holder.name = (TextView) convertView.findViewById(R.id.user_name);
				holder.comment = (TextView) convertView.findViewById(R.id.user_comment);
				holder.time = (TextView) convertView.findViewById(R.id.created_time);
//				holder.btnLike = (TextView) convertView.findViewById(R.id.btn_like);
//				holder.likeNumber = (TextView) convertView.findViewById(R.id.like_number);
//				holder.imageLike = (ImageView) convertView.findViewById(R.id.ic_like);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			FBComments comment = getItem(position);
			if(comment != null){
				AQuery aq = new AQuery(convertView);
				aq.id(holder.avatar).image(comment.getAvatar(), false, true, 0, 0, null, AQuery.FADE_IN_NETWORK, 1.0f/1.0f);
				aq.id(holder.name).text(comment.getName());
				aq.id(holder.comment).text(comment.getContent());
				aq.id(holder.time).text(printTime(comment.getTime()));
//				if(comment.isUserLike()){
//					aq.id(holder.btnLike).text(Html.fromHtml("<u>"+getString(R.string.unlike_action) + "</u>"));
//				} else {
//					aq.id(holder.btnLike).text(Html.fromHtml("<u>"+getString(R.string.like_action) + "</u>"));
//				}
				//int likeCount = comment.getLikeCount();
//				aq.id(holder.likeNumber).invisible();
//				aq.id(holder.imageLike).invisible();
//				if(likeCount == 0){
//					aq.id(holder.likeNumber).invisible();
//					aq.id(holder.imageLike).invisible();
//				} else {
//					aq.id(holder.likeNumber).visible();
//					aq.id(holder.imageLike).visible();
//					aq.id(holder.likeNumber).text(likeCount + "");
//				}
			}
			return convertView;
		}

		public FBCommentAdapter(Context context, int resource, List<FBComments> objects) {
			super(context, resource, objects);
			// TODO Auto-generated constructor stub
		}
		
	}
	
	private String printTime(long inputTime){
		String printedTime = "";
		long time;
		if(inputTime >= (System.currentTimeMillis()/1000L)){
			time = inputTime - (System.currentTimeMillis()/1000L);
		} else {
			time = (System.currentTimeMillis()/1000L) - inputTime;
		}
		long factTime = time / 60;
		System.err.println("time: " + time + " facttime: " + factTime);
		if(factTime < 60){
			if(Math.round(factTime) == 1){
				printedTime = String.format(getString(R.string.minute_ago), factTime);
			} else if(Math.round(factTime) == 0){
				printedTime = String.format(getString(R.string.just_now), factTime);
			} else {
				printedTime = String.format(getString(R.string.minutes_ago), factTime);
			}
		} else {
			factTime = factTime / 60;
			if(Math.round(factTime) < 24){
				if(Math.round(factTime) == 1){
					printedTime = String.format(getString(R.string.hour_ago), factTime);
				} else {
					printedTime = String.format(getString(R.string.hours_ago), factTime);
				}
			} else {
				factTime = factTime / 24;
				if(Math.round(factTime) < 7){
					if(Math.round(factTime) == 1){
						printedTime = String.format(getString(R.string.yesterday), Utils.printTime(inputTime));
					} else {
						printedTime = String.format(getString(R.string.days_ago), factTime);
					}
				} else {
					factTime = factTime / 7;
					if(Math.round(factTime) == 1){
						printedTime = String.format(getString(R.string.week_ago), factTime);
					} else {
						printedTime = String.format(getString(R.string.weeks_ago), factTime);
					}
				}
			}
		} 
		return printedTime;
	}
	
	private class ViewHolder {
		ImageView avatar;
		TextView name;
		TextView comment;
		TextView time;
//		ImageView imageLike;
//		TextView likeNumber;
	}
	
//	public void onEventMainThread(GetDownloadLinkSuccess event){
//		if(pDialog != null){
//			pDialog.dismiss();
//		}
//		DownloadLink download = event.getDl();
//		String url = download.getDownload();
//		Uri srcUri = Uri.parse(url);
//		DownloadManager.Request request = new Request(srcUri);
//		request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
//		request.setTitle(feedItem.getTitle());
//		request.setDescription(feedItem.getImage());
//		request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
//		mDownloadManager.enqueue(request);
//	}
//	
//	public void onEventMainThread(GetDownloadLinkFailEvent e){
//		if(pDialog != null && pDialog.isShowing()){
//			pDialog.dismiss();
//		}
//		AppMsg.makeText(this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
//	}
	
	public void onEventMainThread(FeedListFailEvent event){
		AppMsg.makeText(this, event.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(RequestFailEvent event){
		ErrorHandler.getInstance().setContext(this).handleError(event.getErrorCode());
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
//		IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
//		registerReceiver(downloadReceiver, intentFilter);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void onEventMainThread(getFeedCommentFail e){
		listView.onLoadMoreComplete();
		listView.setOnLoadMoreListener(null);
	}

	@Override
	public void onRefresh(PullToRefreshListView listView) {
		// TODO Auto-generated method stub
		adapter.clear();
		getComments(objectId, commentLimit);
		getLikes(objectId);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		//adapter.clear();
		isLoadMore = true;
		commentLimit = commentLimit + 50;
		getComments(objectId, commentLimit);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_like:
			konnectFacebook();
			if(userLikes){
				action = "unlike"; 
			} else {
				action = "like";
			}
			break;
		case R.id.btn_send:
			if(TextUtils.isEmpty( aq.id(R.id.edit_comment).getText().toString())){
				Toast.makeText(this, R.string.comment_empty, Toast.LENGTH_SHORT).show();
			} else {
				konnectFacebook();
				action = "comment";
			}
			break;
		case R.id.btn_install:
			EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.NEWSFEED_DOWNLOAD, httpURL, Long.valueOf(1));
			if(httpURL.contains("?id=")){
				String packageName = httpURL.substring(httpURL.indexOf("?id=") + 4, httpURL.length());
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, packageName, Long.valueOf(1));
				Intent intent = new Intent(FeedDetailsActivity.this, ItemBrokerActivity.class);
				intent.putExtra(Constants.PREVIOUS_SCREEN, "FeedDetails");
				intent.putExtra(Constants.PACKAGE_NAME, packageName);
				intent.putExtra(Constants.KEY_REFERER, "direct");
				intent.putExtra(Constants.STORE_KEY, "apps");
				startActivity(intent);
			} else {
				pDialog = ProgressDialogManager.showProgressDialog(FeedDetailsActivity.this, R.string.loading);
				accessToken = Utils.getStaticAccessToken(FeedDetailsActivity.this);
				bgTask.convertLink(accessToken, httpURL);
			}
			break;
		}
	}
	
	public void onEventMainThread(ConvertLinkSuccess e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		String store = e.getStore();
		if(store.equalsIgnoreCase("ebook")){
			store = "books";
		} else if(store.equalsIgnoreCase("comic")){
			store = "comics";
		} else {
			store = "apps";
		}
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, e.getSlug(), Long.valueOf(1));
		if(e.getSlug().startsWith("market")||e.getSlug().startsWith("http")){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(e.getSlug())));
				} catch (android.content.ActivityNotFoundException anfe) {
				}
		}else{
			Intent intent = new Intent(FeedDetailsActivity.this, ItemBrokerActivity.class);
			intent.putExtra(Constants.PREVIOUS_SCREEN, "NewsFeed");
			intent.putExtra(Constants.SLUG, e.getSlug());
			intent.putExtra(Constants.KEY_REFERER, "direct");
			intent.putExtra(Constants.STORE_KEY, store);
			startActivity(intent);
		}
		
	}
	
	public void onEventMainThread(ConvertLinkFail e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
	}
	
	private void konnectFacebook(){
		String permissions[] = {"email", "read_stream","publish_stream", "read_friendlists"};
		FB_APP_ID = getResources().getString(R.string.fb_app_id);
		fbLoginManager = new FBLoginManager(this, R.layout.activity_login, FB_APP_ID, permissions);
		if(fbLoginManager.existsSavedFacebook()){
			fbLoginManager.loadFacebook();
		} else {
			fbLoginManager.login();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		try {
			fbLoginManager.loginSuccess(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void loginSuccess(Facebook facebook) {
		// TODO Auto-generated method stub
		pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
		if(action.equalsIgnoreCase("like")){
			bgTask.like(facebook.getAccessToken(), objectId);
		} else if(action.equalsIgnoreCase("unlike")){
			bgTask.unlike(facebook.getAccessToken(), objectId);
		} else {
			bgTask.commentFB(facebook.getAccessToken(), objectId, aq.id(R.id.edit_comment).getText().toString());
		}
	}

	@Override
	public void logoutSuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void loginFail() {
		// TODO Auto-generated method stub
		
	}
	
	public void onEventMainThread(CommentFBSuccess e){
		adapter.clear();
		getComments(objectId, commentLimit);
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(aq.id(R.id.edit_comment).getEditText().getWindowToken(), 0);
		aq.id(R.id.edit_comment).text("");
		if(userLikes){
			action = "unlike"; 
		} else {
			action = "like";
		}
	}
	
	public void onEventMainThread(LikeSuccessEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		userLikes = true;
		headerAQ.id(R.id.btn_like).text(R.string.unlike_action).clicked(this);
	}
	
	public void onEventMainThread(UnLikeSuccessEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		userLikes = false;
		headerAQ.id(R.id.btn_like).text(R.string.like_action).clicked(this);
	}
	
	public void onEventMainThread(LikeFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}
	
	public void onEventMainThread(UnLikeFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}
}
